// scene.jsx — calm click-through animation

const { useMemo } = React;

// simple lerp helper
const lerp = (t, a, b) => a + (b - a) * t;

// ── Palette ───────────────────────────────────────────────────────────────
const C = {
  bg: '#fbfaf7',
  wash: '#eceaf7',
  ink: '#0f1a3a',
  sub: '#5b6478',
  accent: '#6b5bd6',
  accentSoft: '#8d80e3',
  line: '#e6e4ef',
  card: '#ffffff',
  chipA: '#f4cc4a',
  chipB: '#b5c0ff',
  chipC: '#f2b0b0',
  chipD: '#c9e3d4',
};

// ── Shared chrome ─────────────────────────────────────────────────────────
const NavBar = ({ mode = 'landing' }) => (
  <div style={{
    position: 'absolute', top: 0, left: 0, right: 0, height: 64,
    display: 'flex', alignItems: 'center', padding: '0 40px',
    background: mode === 'selector' ? '#fff' : 'transparent',
    borderBottom: mode === 'selector' ? `1px solid ${C.line}` : 'none',
    zIndex: 5,
  }}>
    {mode === 'landing' ? (
      <>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{
            width: 22, height: 22, borderRadius: 5,
            background: C.accent, display: 'grid', placeItems: 'center',
          }}>
            <div style={{ width: 10, height: 10, borderRadius: 2, background: '#fff', opacity: 0.9 }} />
          </div>
          <div style={{ color: C.accent, fontWeight: 700, fontSize: 16, letterSpacing: -0.2 }}>
            Collectively
          </div>
        </div>
        <div style={{ display: 'flex', gap: 28, marginLeft: 48 }}>
          <div style={{ fontSize: 14, color: C.ink, fontWeight: 600 }}>View Groups</div>
          <div style={{ fontSize: 14, color: C.sub }}>Dashboard</div>
        </div>
        <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 8 }}>
          <div style={{
            width: 28, height: 28, borderRadius: '50%',
            background: '#dfe8ff', color: C.accent,
            display: 'grid', placeItems: 'center',
            fontSize: 12, fontWeight: 700,
          }}>M</div>
          <div style={{ fontSize: 13, color: C.ink }}>Maya ▾</div>
        </div>
      </>
    ) : (
      <>
        <div style={{ fontSize: 13, color: C.sub, marginRight: 32 }}>Your selections</div>
        <div style={{ display: 'flex', gap: 8 }}>
          <SelBadge n="1" color={C.chipA} />
          <SelBadge n="2" color={C.chipA} />
          <SelBadge n="3" color={C.chipA} />
          <SelBadge n="…" color="#e9e7f1" text={C.sub} />
        </div>
        <div style={{
          flex: 1, margin: '0 40px', height: 32, borderRadius: 6,
          background: '#f2f0f7', display: 'flex', alignItems: 'center',
          padding: '0 14px', fontSize: 13, color: C.sub,
        }}>
          Rivers & Watershed Futures
        </div>
        <div style={{
          padding: '8px 22px', borderRadius: 6, background: C.accent,
          color: '#fff', fontSize: 13, fontWeight: 600,
        }}>Submit</div>
      </>
    )}
  </div>
);

const SelBadge = ({ n, color, text = '#7a5a00' }) => (
  <div style={{
    width: 28, height: 28, borderRadius: 5, background: color,
    display: 'grid', placeItems: 'center',
    fontSize: 13, fontWeight: 700, color: text,
  }}>{n}</div>
);

// ── Landing scene ─────────────────────────────────────────────────────────
const Landing = ({ pageProgress, buttonPressed, cursor }) => {
  // pageProgress: 0..1 — how "out" the landing is (0 in place, 1 gone up)
  const lift = lerp(Easing.easeInCubic(pageProgress), 0, -40);
  const fade = 1 - Easing.easeInQuad(clamp(pageProgress / 0.7, 0, 1));

  return (
    <div style={{
      position: 'absolute', inset: 0,
      transform: `translateY(${lift}px)`,
      opacity: fade,
      background: C.bg,
    }}>
      <NavBar mode="landing" />

      {/* Hero */}
      <div style={{
        position: 'absolute', top: 140, left: 80, right: 80,
        display: 'flex', alignItems: 'center', gap: 80,
      }}>
        <div style={{ flex: 1 }}>
          <div style={{
            fontSize: 56, fontWeight: 800, color: C.ink,
            letterSpacing: -1.5, lineHeight: 1, marginBottom: 20,
          }}>Collectively</div>
          <div style={{
            fontSize: 15, color: C.sub, lineHeight: 1.55,
            maxWidth: 380, marginBottom: 32,
          }}>
            Join a reading circle to explore research in subjects
            ranging from Machine Learning to Environmental Policy.
          </div>
          <ViewGroupsButton pressed={buttonPressed} />
        </div>

        {/* Abstract hero placeholder — geometric, calm */}
        <HeroArt />
      </div>

      {/* Wave divider */}
      <svg
        style={{ position: 'absolute', left: 0, right: 0, top: 460, width: '100%' }}
        viewBox="0 0 1280 80" preserveAspectRatio="none" height="80"
      >
        <path d="M0,40 C320,10 640,70 960,40 C1120,25 1200,35 1280,30 L1280,80 L0,80 Z"
              fill={C.wash} />
      </svg>

      {/* Lower wash band */}
      <div style={{
        position: 'absolute', left: 0, right: 0, top: 540, bottom: 0,
        background: C.wash,
      }}>
        <div style={{
          position: 'absolute', top: 40, left: 80, right: 80,
          display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 24,
        }}>
          <QuoteCard name="Priya Naidu" initial="P" role="BIOL c/o 2020 | Research Analyst, Helix"
            text={'"The discussions pushed me to read papers I never would have found on my own."'} />
          <FeatureCard title="Explore Emerging Research" hue={C.accentSoft} />
          <div style={{ paddingTop: 8 }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: C.accent, letterSpacing: 1.4 }}>WHAT IS IT?</div>
            <div style={{ fontSize: 26, fontWeight: 800, color: C.ink, marginTop: 8, lineHeight: 1.15 }}>
              Weekly Reading<br/>Circles
            </div>
            <div style={{ fontSize: 13, color: C.sub, marginTop: 12, lineHeight: 1.55, maxWidth: 260 }}>
              Circles meet to read a research paper together and discuss it in a small, relaxed setting.
            </div>
          </div>
        </div>
      </div>

      {/* Cursor (lives in landing layer until click happens) */}
      {cursor && <Cursor x={cursor.x} y={cursor.y} />}
    </div>
  );
};

const HeroArt = () => (
  <div style={{ flex: 1, position: 'relative', height: 240 }}>
    {/* chart panel */}
    <div style={{
      position: 'absolute', left: 20, top: 0, width: 150, height: 110,
      background: '#fff', borderRadius: 10, border: `1px solid ${C.line}`,
      boxShadow: '0 6px 20px rgba(30,20,80,0.06)', padding: 14,
    }}>
      <svg width="120" height="60" viewBox="0 0 120 60">
        <polyline points="0,50 20,40 40,45 60,25 80,30 100,12 120,18"
          fill="none" stroke={C.accent} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
        <polyline points="0,55 20,48 40,52 60,40 80,42 100,30 120,35"
          fill="none" stroke={C.chipC} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" opacity="0.7"/>
      </svg>
      <div style={{ height: 6, background: '#f0eef8', borderRadius: 3, marginTop: 8 }} />
    </div>
    {/* donut panel */}
    <div style={{
      position: 'absolute', left: 190, top: 20, width: 110, height: 90,
      background: '#fff', borderRadius: 10, border: `1px solid ${C.line}`,
      boxShadow: '0 6px 20px rgba(30,20,80,0.06)',
      display: 'grid', placeItems: 'center',
    }}>
      <Donut color={C.accent} pct={0.7} />
    </div>
    <div style={{
      position: 'absolute', left: 310, top: 20, width: 110, height: 90,
      background: '#fff', borderRadius: 10, border: `1px solid ${C.line}`,
      boxShadow: '0 6px 20px rgba(30,20,80,0.06)',
      display: 'grid', placeItems: 'center',
    }}>
      <Donut color={C.chipC} pct={0.45} />
    </div>

    {/* three floating seat blobs (calm, abstract) */}
    <FigureBlob x={40} y={130} color={C.ink} />
    <FigureBlob x={170} y={140} color={C.accent} />
    <FigureBlob x={290} y={140} color={'#e88a6a'} />
  </div>
);

const Donut = ({ color, pct }) => {
  const R = 24, C2 = 2 * Math.PI * R;
  return (
    <svg width="64" height="64" viewBox="-32 -32 64 64">
      <circle r={R} fill="none" stroke="#eceaf7" strokeWidth="8" />
      <circle r={R} fill="none" stroke={color} strokeWidth="8"
        strokeDasharray={`${C2 * pct} ${C2}`} strokeLinecap="round"
        transform="rotate(-90)" />
    </svg>
  );
};

const FigureBlob = ({ x, y, color }) => (
  <div style={{
    position: 'absolute', left: x, top: y, width: 70, height: 100,
  }}>
    <div style={{
      position: 'absolute', top: 0, left: 18, width: 34, height: 34,
      borderRadius: '50%', background: color, opacity: 0.9,
    }} />
    <div style={{
      position: 'absolute', top: 30, left: 5, width: 60, height: 60,
      borderRadius: '30px 30px 14px 14px', background: color, opacity: 0.85,
    }} />
    <div style={{
      position: 'absolute', bottom: 0, left: 12, width: 46, height: 8,
      borderRadius: 4, background: '#222', opacity: 0.9,
    }} />
  </div>
);

const ViewGroupsButton = ({ pressed }) => {
  // pressed: 0..1 — scale down briefly on click
  const scale = 1 - pressed * 0.06;
  return (
    <div style={{
      display: 'inline-block',
      padding: '14px 26px', borderRadius: 10, background: C.accent,
      color: '#fff', fontSize: 15, fontWeight: 600,
      boxShadow: `0 ${8 - pressed * 5}px ${20 - pressed * 10}px rgba(107,91,214,${0.35 - pressed * 0.2})`,
      transform: `scale(${scale})`,
      position: 'relative',
    }}>
      View Groups
    </div>
  );
};

const QuoteCard = ({ name, role, text, initial = 'J' }) => (
  <div style={{
    background: '#fff', borderRadius: 10, padding: 18,
    boxShadow: '0 4px 14px rgba(20,20,60,0.05)',
  }}>
    <div style={{ fontSize: 12, color: C.sub, lineHeight: 1.5, minHeight: 72 }}>{text}</div>
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 14 }}>
      <div style={{
        width: 28, height: 28, borderRadius: '50%', background: '#d4c0b0',
        display: 'grid', placeItems: 'center',
        fontSize: 12, fontWeight: 700, color: '#fff',
      }}>{initial}</div>
      <div>
        <div style={{ fontSize: 12, fontWeight: 700, color: C.ink }}>{name}</div>
        <div style={{ fontSize: 10, color: C.sub }}>{role}</div>
      </div>
    </div>
  </div>
);

const FeatureCard = ({ title, hue }) => (
  <div style={{
    background: '#fff', borderRadius: 10, padding: 18,
    boxShadow: '0 4px 14px rgba(20,20,60,0.05)',
    display: 'flex', flexDirection: 'column', alignItems: 'center',
  }}>
    <div style={{ fontSize: 13, fontWeight: 700, color: C.ink, textAlign: 'center', marginBottom: 14 }}>
      {title}
    </div>
    <div style={{
      width: 80, height: 80, borderRadius: '50%',
      background: '#eaf2ff', display: 'grid', placeItems: 'center',
    }}>
      <div style={{
        width: 40, height: 24, borderRadius: '20px 20px 4px 4px',
        background: hue,
      }} />
    </div>
  </div>
);

// ── Cursor ────────────────────────────────────────────────────────────────
const Cursor = ({ x, y, ripple = 0 }) => (
  <>
    {ripple > 0 && (
      <div style={{
        position: 'absolute', left: x - 30, top: y - 30,
        width: 60, height: 60, borderRadius: '50%',
        border: `2px solid ${C.accent}`,
        opacity: 1 - ripple,
        transform: `scale(${0.3 + ripple * 1.6})`,
        pointerEvents: 'none', zIndex: 30,
      }} />
    )}
    <svg width="22" height="26" viewBox="0 0 22 26" style={{
      position: 'absolute', left: x, top: y, zIndex: 31,
      filter: 'drop-shadow(0 2px 4px rgba(0,0,0,0.18))',
    }}>
      <path d="M2,2 L2,20 L7,16 L10,22 L13,21 L10,15 L17,15 Z"
        fill="#fff" stroke="#0f1a3a" strokeWidth="1.4" strokeLinejoin="round"/>
    </svg>
  </>
);

// ── Selector / groups scene ───────────────────────────────────────────────
const Selector = ({ pageProgress, gridFade, cursor, cardPulse, modalProgress }) => {
  // pageProgress: 0..1 — 0 = offscreen below, 1 = in place
  const slide = lerp(Easing.easeOutCubic(pageProgress), 40, 0);
  const fade = Easing.easeOutQuad(pageProgress);

  return (
    <div style={{
      position: 'absolute', inset: 0,
      transform: `translateY(${slide}px)`,
      opacity: fade,
      background: C.bg,
      pointerEvents: 'none',
    }}>
      <NavBar mode="selector" />

      {/* Grid */}
      <div style={{
        position: 'absolute', top: 96, left: 80, right: 420, bottom: 40,
        display: 'grid', gridTemplateColumns: '1fr 1fr',
        gap: 18, opacity: gridFade,
      }}>
        <GroupCard title="Foundations of Neural Networks" org="Mindframe Collective" chip={C.chipA} delay={0} gridFade={gridFade} />
        <GroupCard title="Urban Mobility & Public Space" org="Civic Studio" chip={C.chipC} delay={0.08} gridFade={gridFade} />
        <GroupCard title="Rivers & Watershed Futures" org="Greenline Research" chip={C.chipB} delay={0.16} gridFade={gridFade} highlight={cardPulse} />
        <GroupCard title="Ethics of Large Models" org="Openloop Lab" chip={C.chipC} delay={0.24} gridFade={gridFade} />
        <GroupCard title="Design for Aging Populations" org="Longview Group" chip={C.chipB} delay={0.32} gridFade={gridFade} />
        <GroupCard title="History of Scientific Illustration" org="Atlas Readers" chip={C.chipC} delay={0.40} gridFade={gridFade} />
      </div>

      {/* Scrollbar hint */}
      <div style={{
        position: 'absolute', right: 400, top: 160, bottom: 80,
        width: 4, background: '#ececf5', borderRadius: 2, opacity: gridFade * 0.8,
      }}>
        <div style={{ position: 'absolute', top: 40, width: 4, height: 60, background: '#c8c5e0', borderRadius: 2 }} />
      </div>

      {/* Detail modal */}
      <DetailModal progress={modalProgress} />

      {cursor && <Cursor x={cursor.x} y={cursor.y} ripple={cursor.ripple || 0} />}
    </div>
  );
};

const GroupCard = ({ title, org = 'Organizer', chip, delay, gridFade, highlight = 0 }) => {
  const localFade = clamp((gridFade - delay) / 0.3, 0, 1);
  const rise = (1 - localFade) * 14;
  return (
    <div style={{
      background: '#fff',
      border: highlight > 0 ? `2px solid ${C.accent}` : `1px solid ${C.line}`,
      boxShadow: highlight > 0
        ? `0 8px 24px rgba(107,91,214,${0.2 * highlight})`
        : '0 2px 8px rgba(20,20,60,0.04)',
      borderRadius: 10, padding: 16,
      opacity: localFade,
      transform: `translateY(${rise}px)`,
      transition: 'none',
      minHeight: 130,
      display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
    }}>
      <div style={{ fontSize: 16, fontWeight: 700, color: C.ink, lineHeight: 1.2 }}>{title}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <div style={{
          width: 22, height: 22, borderRadius: '50%', background: chip,
          display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 700,
          color: '#fff',
        }}>{(org || 'Organizer')[0]}</div>
        <div style={{ fontSize: 11, color: C.sub }}>
          <div style={{ fontWeight: 600, color: C.ink }}>Organizer</div>
          {org}
        </div>
      </div>
    </div>
  );
};

const DetailModal = ({ progress }) => {
  if (progress <= 0) return null;
  const rise = lerp(Easing.easeOutCubic(progress), 30, 0);
  const opacity = Easing.easeOutQuad(clamp(progress / 0.6, 0, 1));
  return (
    <div style={{
      position: 'absolute', right: 40, top: 88, width: 360, bottom: 40,
      background: '#fff', borderRadius: 12,
      border: `1px solid ${C.line}`,
      boxShadow: '0 20px 50px rgba(20,20,60,0.12)',
      padding: 24,
      transform: `translateY(${rise}px)`,
      opacity,
    }}>
      {/* side rail */}
      <div style={{
        position: 'absolute', left: -26, top: 30, width: 26, height: 170,
        background: '#fff', borderRadius: '6px 0 0 6px',
        boxShadow: '-6px 4px 18px rgba(20,20,60,0.08)',
        display: 'flex', flexDirection: 'column', alignItems: 'center',
        padding: '12px 0', gap: 8,
      }}>
        <div style={{ fontSize: 8, color: C.sub, writingMode: 'vertical-rl', marginBottom: 6 }}>Select this theme</div>
        <SelBadge n="1" color={C.chipA} />
        <SelBadge n="2" color="#e9e7f1" text={C.sub} />
        <SelBadge n="3" color="#e9e7f1" text={C.sub} />
      </div>

      <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 8 }}>
        <div style={{ fontSize: 18, color: C.sub }}>×</div>
      </div>

      <div style={{
        fontSize: 24, fontWeight: 800, color: C.ink,
        letterSpacing: -0.5, lineHeight: 1.1, marginBottom: 18,
      }}>
        Rivers & Watershed<br/>Futures
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 18 }}>
        <div style={{
          width: 32, height: 32, borderRadius: '50%', background: '#d4c0b0',
          display: 'grid', placeItems: 'center',
          fontSize: 13, fontWeight: 700, color: '#fff',
        }}>EM</div>
        <div>
          <div style={{ fontSize: 10, color: C.sub }}>Organizer</div>
          <div style={{ fontSize: 13, fontWeight: 600, color: C.ink }}>Dr. Elena Moreau</div>
        </div>
      </div>

      <div style={{ height: 1, background: C.line, marginBottom: 16 }} />

      {[0, 1, 2].map(i => (
        <div key={i} style={{ marginBottom: 10 }}>
          <div style={{ height: 6, borderRadius: 3, background: '#ececf5', marginBottom: 6 }} />
          <div style={{ height: 6, borderRadius: 3, background: '#ececf5', marginBottom: 6, width: '92%' }} />
          <div style={{ height: 6, borderRadius: 3, background: '#ececf5', width: '70%' }} />
        </div>
      ))}

      <div style={{
        fontSize: 12, fontWeight: 700, color: C.ink,
        borderBottom: `1px solid ${C.ink}`, display: 'inline-block',
        marginTop: 8, paddingBottom: 2,
      }}>Selected Authors and Publications</div>

      <div style={{ marginTop: 12 }}>
        {['Rowan Ashford', 'Mira Tanaka', 'Sediment Flow in Temperate Estuaries', 'Restoring the Cascara Delta: A Field Study'].map((t, i) => (
          <div key={i} style={{ fontSize: 11, color: C.accent, marginBottom: 6, textDecoration: 'underline' }}>{t}</div>
        ))}
      </div>
    </div>
  );
};

// ── Master scene ──────────────────────────────────────────────────────────
const Scene = () => {
  const t = useTime();

  // Timeline (seconds)
  //  0.0 — 1.2   cursor glides toward "View Groups"
  //  1.2 — 1.5   hover (button subtle)
  //  1.5 — 1.8   click ripple + press
  //  1.8 — 2.8   landing fades/lifts out; selector slides in
  //  2.8 — 3.6   grid cards cascade in
  //  3.6 — 4.8   cursor glides to a card, card highlights
  //  4.8 — 5.2   click on card
  //  5.2 — 6.2   modal rises in
  //  6.2 — 7.0   hold
  //  loops at 7.0

  const TOTAL = 7.0;
  const tt = t % TOTAL;

  // Cursor path in stage coordinates (1280x720)
  // Start resting near bottom-right of hero; move to button at (185, 445).
  const cursorStart = { x: 720, y: 560 };
  const buttonPos = { x: 185, y: 445 };
  const cardPos = { x: 360, y: 340 }; // card in selector

  let cursor = null;
  let buttonPressed = 0;
  let pageProgress = 0; // landing out
  let selectorProgress = 0;
  let gridFade = 0;
  let cardPulse = 0;
  let modalProgress = 0;
  let clickRipple = 0;

  if (tt < 1.2) {
    // glide to button
    const p = Easing.easeInOutCubic(tt / 1.2);
    cursor = {
      x: lerp(p, cursorStart.x, buttonPos.x),
      y: lerp(p, cursorStart.y, buttonPos.y),
    };
  } else if (tt < 1.5) {
    cursor = { ...buttonPos };
    buttonPressed = 0;
  } else if (tt < 1.8) {
    // click press + ripple
    const p = (tt - 1.5) / 0.3;
    cursor = { ...buttonPos, ripple: p };
    buttonPressed = p < 0.5 ? p * 2 : (1 - p) * 2;
    clickRipple = p;
  } else if (tt < 2.8) {
    // transition
    const p = (tt - 1.8) / 1.0;
    pageProgress = Easing.easeInOutCubic(p);
    selectorProgress = Easing.easeInOutCubic(p);
    cursor = null; // hide during transition for calm
  } else if (tt < 3.6) {
    pageProgress = 1;
    selectorProgress = 1;
    gridFade = Easing.easeOutQuad((tt - 2.8) / 0.8);
    cursor = null;
  } else if (tt < 4.8) {
    pageProgress = 1;
    selectorProgress = 1;
    gridFade = 1;
    // cursor glides from offscreen-ish to card
    const p = Easing.easeInOutCubic((tt - 3.6) / 1.2);
    cursor = {
      x: lerp(p, 800, cardPos.x),
      y: lerp(p, 600, cardPos.y),
    };
    cardPulse = clamp((tt - 4.2) / 0.6, 0, 1);
  } else if (tt < 5.2) {
    pageProgress = 1; selectorProgress = 1; gridFade = 1;
    const p = (tt - 4.8) / 0.4;
    cursor = { ...cardPos, ripple: p };
    cardPulse = 1;
  } else if (tt < 6.2) {
    pageProgress = 1; selectorProgress = 1; gridFade = 1;
    cardPulse = 1;
    modalProgress = Easing.easeOutCubic((tt - 5.2) / 1.0);
    cursor = { ...cardPos };
  } else {
    pageProgress = 1; selectorProgress = 1; gridFade = 1;
    cardPulse = 1; modalProgress = 1;
    cursor = { ...cardPos };
  }

  // Show landing on top until pageProgress catches up; then selector on top.
  return (
    <>
      {/* Selector sits underneath landing */}
      <Selector
        pageProgress={selectorProgress}
        gridFade={gridFade}
        cursor={pageProgress >= 1 ? cursor : null}
        cardPulse={cardPulse}
        modalProgress={modalProgress}
      />
      {pageProgress < 1 && (
        <Landing
          pageProgress={pageProgress}
          buttonPressed={buttonPressed}
          cursor={cursor}
        />
      )}
    </>
  );
};

Object.assign(window, { Scene });
